//
//  CYMessageViewController.m
//  cyjf
//
//  Created by tauCross on 2017/9/28.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYMessageViewController.h"

#import <WebKit/WebKit.h>



@interface CYMessageViewController ()<WKNavigationDelegate>

@property(nonatomic, strong)WKWebView *webView;

@end


@implementation CYMessageViewController

- (void)loadUI
{
    self.navigationItem.title = @"消息中心";
    self.tableView.hidden = YES;

    self.webView = [[WKWebView alloc] init];
    [self.contentView addSubview:self.webView];
    self.webView.allowsBackForwardNavigationGestures = YES;
    self.webView.navigationDelegate = self;
    NSString *url = [CY_H5_BASE_URL stringByAppendingFormat:@"views/message_center.html?token=%@", CYStandardAuthManager.currentAuth.token];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url.tc_url]];
}

- (void)showAllReadButton
{
    UIButton *allReadButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [allReadButton setTintColor:HEXCOLOR(@"444444")];
    [allReadButton setTitle:@"全部已读" forState:UIControlStateNormal];
    allReadButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [allReadButton sizeToFit];
    [allReadButton addTarget:self action:@selector(allReadAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:allReadButton];
}

- (void)hideAllReadButton
{
    self.navigationItem.rightBarButtonItem = nil;
}

- (void)layoutUI
{
    self.webView.frame = self.contentView.bounds;
}

- (void)allReadAction
{
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI message_readAllWithType:CYDataAPIMessageTypePerson complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            [SVProgressHUD dismiss];
            [self.webView reload];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

- (void)back
{
    if(self.webView.canGoBack)
    {
        [self.webView goBack];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)checkAllReadButton
{
    if(self.webView.canGoBack)
    {
        [self hideAllReadButton];
    }
    else
    {
        [self showAllReadButton];
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self checkAllReadButton];
}

@end
